package com.heima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.dto.ContractPageQueryDto;
import com.heima.mapper.ContractMapper;

import com.heima.pojo.Contract;
import com.heima.service.ContractService;
import com.heima.util.RandomUtil;
import com.heima.vo.ContractVo;
import com.heima.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
public class ContractServiceImpl implements ContractService {
    @Autowired
    private ContractMapper contractMapper;
    private final RandomUtil randomUtil = new RandomUtil();

    /**
     * 分页查询
     * @param contractPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQueryContract(ContractPageQueryDto contractPageQueryDTO) {
        PageHelper.startPage(contractPageQueryDTO.getPageNum(),contractPageQueryDTO.getPageSize());
        Page<ContractVo> page = contractMapper.pageQueryContract(contractPageQueryDTO);
        PageResult result = new PageResult();
        result.setTotal(page.getTotal());
        result.setRows(page.getResult());
        return result;
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public ContractVo getById(Long id) {
        ContractVo contractVO = contractMapper.getById(id);
        return contractVO;
    }

    /**
     * 修改合同信息
     * @param contractVo
     */
    @Override
    public void updateContract(ContractVo contractVo) {
        contractMapper.updateContract(contractVo);
    }

    /**
     * 新增合同
     * @param contractVo
     */
    @Override
    public void addContract(ContractVo contractVo) {
        Contract contract = new Contract();
        String randomId= randomUtil.getRandomNumber();
        contract.setContractNo(randomId);
        contract.setName(contractVo.getName());
        contract.setPhone(contractVo.getPhone());
        contract.setSubject(contractVo.getSubject());
        contract.setCourseId(contractVo.getCourseId());
        contract.setActivityId(contractVo.getActivityId());
        //根据活动id查询活动表里的活动名称并更新到合同表中
        contract.setActiveName(contractMapper.getActiveName(contractVo.getActivityId()));
        contract.setChannel(contractVo.getChannel());
        //根据渠道id查询字典表里的渠道名称并更新到合同表中
        contract.setChannelName(contractMapper.getChannelName(contractVo.getChannel()));
        contract.setCreateTime(LocalDateTime.now());
        contractMapper.addContract(contract);
    }
}
